package com.yfjin.gl.filter;

import android.content.Context;
import android.opengl.GLES20;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

abstract public class AbstractFilter {

    protected final int program;

    private final int vPosition;
    private final int vCoord;
    private final int vTexture;


    private final FloatBuffer vertexBuffer;
    float[] VERTEX={
            -1f,-1f,
            1f,-1f,
            -1f,1f,
            1f,1f
    };

    private final FloatBuffer textureBuffer;
    float[] TEXTURE={
            0.0f, 0.0f,
            1.0f, 0.0f,
            0.0f, 1.0f,
            1.0f, 1.0f
    };


    protected int mWidth;
    protected int mHeight;

    public AbstractFilter(Context context,int vertexShaderId,int fragShaderId) {

        //allocateDirect是连续的allocate可能是分段的内存
        //4个坐标 每个坐标float类型4个字节  一个x一个y=2
        vertexBuffer= ByteBuffer.allocateDirect(4*4*2).order(ByteOrder.nativeOrder()).asFloatBuffer();
        vertexBuffer.clear();
        vertexBuffer.put(VERTEX);


        textureBuffer=ByteBuffer.allocateDirect(4*4*2).order(ByteOrder.nativeOrder()).asFloatBuffer();
        textureBuffer.clear();
        textureBuffer.put(TEXTURE);


        String vertexShader=OpenGLUtils.readRawTextFile(context,vertexShaderId);
        String fragShader=OpenGLUtils.readRawTextFile(context,fragShaderId);
        //编译-》连接-》运行

        program=OpenGLUtils.loadProgram(vertexShader,fragShader);

        vPosition= GLES20.glGetAttribLocation(program,"vPosition");
        vCoord= GLES20.glGetAttribLocation(program,"vCoord");
        vTexture= GLES20.glGetUniformLocation(program,"vTexture");
    }

    public void setSize(int width, int height) {
        mWidth=width;
        mHeight=height;
    }



    public int onDraw(int texture) {
        GLES20.glViewport(0,0,mWidth,mHeight);
        GLES20.glUseProgram(program);


        vertexBuffer.position(0);
        //2=每个顶点的个数
        GLES20.glVertexAttribPointer(vPosition,2,GLES20.GL_FLOAT,false,0,vertexBuffer);
        GLES20.glEnableVertexAttribArray(vPosition);



        textureBuffer.position(0);
        GLES20.glVertexAttribPointer(vCoord,2,GLES20.GL_FLOAT,false,0,textureBuffer);
        GLES20.glEnableVertexAttribArray(vCoord);



        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,texture);
        GLES20.glUniform1f(vTexture,0);


        beforeDraw();

        //通知画画，
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP,0,4);

        return texture;
    }

    protected abstract void beforeDraw();

    public void release(){
        GLES20.glDeleteProgram(program);
    }
}
